<?php
namespace Admin\Controller;
use Admin\Common\Page;
class ClassController extends BaseController
{
    //                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖镇楼                  BUG辟易
//             佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
    /**
     * 班级列表
     */
    public function index()
    {
        $child_school_id = I('get.child_school_id');
        $class = M('Class');
        if($child_school_id)
        {
            $count = $class->where("child_school_id=$child_school_id")->where("status=0")->count();
        }
        else{
            $count = $class->where("status=0")->count();
        }
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        if($child_school_id)
        {
            $classdata = $class->table('class a ')->field('a.*,b.name,b.id as cid')->join('JOIN child_school b on a.child_school_id = b.id')->where("a.status=0 and a.child_school_id=$child_school_id")->limit($Page->firstRow . ',' . $Page->listRows)->select();
           // dump($classdata);die;
        }
        else{
            $classdata = $class->table('class a ')->join('JOIN child_school b on a.child_school_id = b.id')->limit($Page->firstRow . ',' . $Page->listRows)->where("a.status=0")->select();
        }
        $this->assign('classdata',$classdata);
        $this->display();

    }
    /**
     * 添加班级
     */
    public function add(){
        $class = M('Class');
        if(IS_POST){
            $data = I('post.');
            if(M('class')->where("child_school_id=".$data['child_school_id']." and class_name='{$data['name2']}'")->find()){
                $this->error('幼儿园班级名称重复');
            }
            $arr =[
                'class_name' => $data['name2'],
                'child_school_id' => $data['child_school_id'],
            ];
            $res = $class->data($arr)->add();
            if($res){
                $this->success('添加成功',U('index',array('child_school_id'=>$data['child_school_id'])));

            }
            $this->error('添加失败');
        }else{
            $childschool_all  = M('Child_school')->where('status=0')->select();
            $this->assign('childschool_data',$childschool_all);
            $this->assign("child_school_id", I("get.child_school_id"));
            $this->display();
        }
    }
    /**
     * 批量添加班级
     */
    public function addClass()
    {
        $class = D('class');
        if (IS_POST) {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 3145728;// 设置附件上传大小
            $upload->exts = ['xls', 'xlsx'];// 设置附件上传类型
            $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
            $upload->savePath = ''; // 设置附件上传（子）目录
            $upload->autoSub = FALSE;
            // 上传文件
            $info = $upload->upload();
            if (!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } else {// 上传成功
                $class = M('class');
                $class->startTrans();
                $data = excel_import($upload->rootPath . $info["excel"]["savename"], $info["excel"]['ext']);
                //第一行为字段
                $colname = $data[1];
                unset($data[1]);
                unset($data[0]);
                $row = 2;
                foreach ($data as $k => $v) {
                   $du = null;
                    $row++;
                    if($v['0'] == '' && $v['1'] == ''){
                        break;
                    }
                    if ($v['0'] == '') {
                        $class->rollback();
                        $this->error('导入出错,班级名称不可为空,错误发生在第' . $row . '行');
                    }
                    if ($v['1'] == '') {
                        $class->rollback();
                        $this->error('导入出错,幼儿园ID不可为空,错误发生在第' . $row . '行');
                    }

                    $du = [
                        $colname['0'] => $v['0'],
                        $colname['1'] => $v['1'],
                    ];
                    $class_id = M('class')->data($du)->add();
                    if (!$class_id) {
                        $class->rollback();
                        $this->error('导入错误,新建班级出错,错误发生在第' . $row . '行');
                    }
                }
                $class->commit();
            }
            //        echo '操作成功';
            $this->success('操作成功');
        }else{
            $this->error('请求方式错误');
        }
    }


    /**
     * 文件导入式 批量添加学生
     */
    public function addStudents()
    {
        if (IS_POST) {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 3145728;// 设置附件上传大小
            $upload->exts = ['xls', 'xlsx'];// 设置附件上传类型
            $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
            $upload->savePath = ''; // 设置附件上传（子）目录
            $upload->autoSub = FALSE;
            // 上传文件
            $info = $upload->upload();
            if (!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } else {// 上传成功
                $student = M('student');
                $student->startTrans();
                $data = excel_import($upload->rootPath . $info["excel"]["savename"], $info["excel"]['ext']);
                //第一行为字段
                $colname = $data[1];
                unset($data[1]);
                unset($data[0]);
                $row = 2;
                foreach ($data as $k => $v) {
                    $du = null;
                    $row++;
                    if($v['0'] == '' && $v['1'] == ''){
                        break;
                    }
                    if ($v['0'] == '') {
                        $student->rollback();
                        $this->error('导入出错,会员卡ID不能为空,错误发生在第' . $row . '行');
                    }
                    if ($v['1'] == '') {
                        $student->rollback();
                        $this->error('导入出错,班级ID不能为空,错误发生在第' . $row . '行');
                    }
                    $card = D('card')->where('card_id='.$v['0'])->field('user_id')->find();
                    $isStu = M('student')->where('status!=4 and card_id='.$v['0'])->find();
                    if($isStu){
                        $student->rollback();
                        $this->error('第'.($row).'行会员已在别的班级中');
                    }

                    if($card){
                        /*有该用户*/
                        $stu = [
                            'user_id' => $card['user_id'],
                            'class_id' => $v['1'],
                            'card_id' => $v['0'],
                            'status' => 0,
                            'bag_id' => 0,
                        ];
                        $key = $student->table('student')->add($stu);
                        if(!$key){
                            $student->rollback();
                            $this->error('第'.($row).'行学生添加失败');
                        }
                    }else{
                        $student->rollback();
                        $this->error('第'.($row).'行会员不存在');
                    }

                }
                $student->commit();
            }
            //        echo '操作成功';
            $this->success('操作成功');
        }else{
            $this->error('请求方式错误');
        }
    }
    /**
     * 修改班级
     */
    public function edit(){
             $class_id = I('get.class_id');
             $childschool_data  = M('Child_school')->select();
             $data = M('Class')->where("id=$class_id")->find();
             $this->assign('childschool_data',$childschool_data);
             $this->assign('data',$data);
             $this->display();


        }
    /**
     * do 修改班级
     */
    public function doedit(){
        $class_id = I('get.class_id');
        $data = I('post.');
        $res = M('Class')->where("id =$class_id")->data($data)->save();
        if($res !==false){
            $this->success('修改成功',U('index',array('child_school_id'=>$data['child_school_id'])));

        }else{
            $this->error('修改失败');

        }



    }

    /**
     * 删除班级
     */
    public function classDel(){
        $class_id = I('get.class_id');
        if($class_id == ""){
            $this->error('参数错误');
        }
        /*先查询班级中是否有绑定的学生*/
        $stus = M()->table('student as s,card as c')->where('s.card_id=c.card_id and s.status=1 and s.class_id='.$class_id)->field('s.*,c.child_name')->select();
        if($stus){
            $names = array();
            foreach ($stus as $k => $stu){
                $names[] = $stu['child_name'];
            }
            $nameStr = trim(implode('、',$names),'、');
            $this->error('该班级内还有未解除绑定的学生:'.$nameStr);
        }else{
            $db = M('');
            $db->startTrans();
            /*证明没有绑定的学生了 先删除学生*/
            $count = $db->table('student')->where('status=0 and class_id='.$class_id)->count();
            if($count==0){
                $db->table('class')->where('id='.$class_id)->save(array('status'=>4));
                $db->commit();
                $this->success('删除班级成功',U('ChildSchool/index'));
            }
            $key1 = $db->table('student')->where('status=0 and class_id='.$class_id)->save(array('status'=>4));
            $key2 = $db->table('class')->where('id='.$class_id)->save(array('status'=>4));
            if($key1 && $key2){
                $db->commit();
                $this->success('删除班级成功',U('ChildSchool/index'));
            }else{
                $db->rollback();
                $this->error('删除班级失败');
            }

        }


    }


    /**
     * 查看班级下的学生
     */
    public function studentList(){
        $class_id = I('get.class_id');
        if($class_id == ""){
            $this->error('参数错误');
        }
        $class =M('Class')->where("id=$class_id")->find();
        if(is_null($class)){
            $this->error('不存在该班级');
        }
        $sql = "SELECT
	            `user`.nickname,student.card_id,student.stu_id,class.class_name,bag.bag_name,bag.bag_card
                FROM
	            `user`,
	            card,
	            class,
	            student
                LEFT JOIN bag ON student.bag_id = bag.bag_id
                WHERE
	            student.`status` != 4
                AND student.user_id=`user`.user_id
                AND student.card_id=card.card_id
                AND	student.class_id=class.id
                AND student.class_id=".$class_id;
        $stuData = M()->query($sql);
       // dump($stuData);die;
        $this->assign('stuData',$stuData);
        $this->display();

    }

    /**
     * 删除学生  将关系表的status 字段改为4  并且更改书的状态
     */

    public function stuDel(){
        /*在模型中开启了 事物  startTrans  暂未 commit 如果 学生剔除后再commit*/
        $stu = M('student')->find(I('get.stu_id'));
        if($stu['bag_id'] != "0"){
            /*证明是有绑定书包*/
            $ids = M('bag_book')->where('status=0 and bag_id='.$stu['bag_id'])->field('book_id')->select();
            $link = D('book')->bookStatus($ids,2);
            if($link == 400){
                $this->error('修改库存出错');
            }
            $key = $link->table('student')->where("stu_id=".I('get.stu_id'))->save(['status'=>4]);
            $key1 = $link->table('bag')->where('bag_id='.$stu['bag_id'])->save(['status'=>0]);
            if($key && $key1){
                $link->commit();
                $this->success("删除成功",U('studentList',array('class_id'=>$stu['class_id'])));
            }else{
                $link->rollback();
                $this->error("删除失败");
            }
        }
        $key2 = M('student')->where("stu_id=".I('get.stu_id'))->save(['status'=>4]);
        if($key2){
            $this->success("删除成功",U('studentList',array('class_id'=>$stu['class_id'])));
        }else{
            $this->error("删除失败");
        }


    }

    /**
     * 学生添加
     */
    public function stuAdd(){
        if(IS_POST){
            //dump($_POST);
            $db = M();
            $db->startTrans();
            foreach($_POST['card_id'] as $k=>$v){
                $card = D('card')->where('card_id='.$v)->field('user_id')->find();
                if($card){
                    /*有该用户*/
                    $stu = [
                        'user_id' => $card['user_id'],
                        'class_id' => $_POST['class_id'],
                        'card_id' => $v,
                        'status' => 0,
                        'bag_id' => 0,
                    ];
                    $isStu = M('student')->where('status!=4 and card_id='.$v)->find();
                    if($isStu){
                        $db->rollback();
                        $this->error('第'.($k+1).'个会员已在别的班级中');
                    }
                    $key = $db->table('student')->add($stu);
                    if(!$key){
                        $db->rollback();
                        $this->error('第'.($k+1).'个会员添加失败');
                    }
                }else{
                    $db->rollback();
                    $this->error('第'.($k+1).'个会员卡不存在');
                }
            }
            $db->commit();
            $this->success('学生添加成功',U('studentList',array('class_id'=>$_POST['class_id'])));
        }else{
            if(I('get.class_id') == ""){
                $this->error("参数错误");
            }
            $class = D('class')->find(I("get.class_id"));
            $this->assign('class',$class);
            $this->display();
        }
    }



    /**
     * 导出班级列表
     */
    public function export(){
            $Class = M('class');
             $classdata = $Class->table('child_school a, class b')->where("b.child_school_id = a.id")->field('b.id as "ID",b.class_name as "班级",a.name "幼儿园"')->select();
             $file = excel_export($classdata);
            ouput_Browser($file);
    }


    /**
     * 一键换书
     *
     * 锁定的学生不参与换书  没有书包的不参与换书
     * z只有status=1的 有书包且不被锁定的学生参与换书
     */
    public function exchange(){
        $classId = I('get.class_id');
        if($classId == ""){
            $this->error('参数错误');
        }
        $db = M();
        $students = $db->table('student')
            ->where('status=1 and class_id='.$classId)
            ->select();
        $num = count($students);
        if($num==0 || $num==1){
            $this->error('该班级没有学生绑定书包或只有一名学生绑定书包');
        }
        $db->startTrans();
        foreach($students as $k=>$student){
            /*最后一名学生用第一名学生的书包*/
            $nums=$k+1;
            $stu_id =  $student['stu_id'];
            unset($student['stu_id']);
            if($num == $nums){
                $student['bag_id'] = $students['0']['bag_id'];
                $key1 = $db->table('student')->where('stu_id='.$stu_id)->save($student);
                $key2 = $db->table('bag')->where('bag_id='.$students['0']['bag_id'])->save(array('stu_id'=>$stu_id));
                if($key1==false || $key2==false){
                    $db->rollback();
                    $this->error('替换失败');
                }
            }else{
                $student['bag_id'] = $students[$nums]['bag_id'];
                $key1 = $db->table('student')->where('stu_id='.$stu_id)->save($student);
                $key2 = $db->table('bag')->where('bag_id='.$students[$nums]['bag_id'])->save(array('stu_id'=>$stu_id));
                if($key1==false || $key2==false){
                    $db->rollback();
                    $this->error('替换失败');
                }
            }

        }
        $db->commit();
        $this->success('换书成功',U('index',array('child_school_id'=>I('get.child_school_id'))));

    }

    /**
     * 整班解绑
     */
    public function allUntie(){
        $classId = I('get.class_id');
        $child_school_id = I('get.child_school_id');
        if($classId == ""){
            $this->error('参数错误');
        }
        $db = M();
        $stuIds = $db->table('student')->where('status=1 and class_id='.$classId)->getField('stu_id',true);
        if($stuIds == NULL){
            $this->error('该班级并没有绑定书包');
        }
        $idsStr = trim(implode(',',$stuIds),',');
        $key1 = $db->table('student')->where('status=1 and class_id='.$classId)->save(array('status'=>0,'bag_id'=>0));
        $key2 = $db->table('bag')->where('stu_id in ('.$idsStr.')')->save(array('stu_id'=>0,'status'=>0));
        if($key2 && $key1){
            $db->commit();
            $this->success('解绑成功',U('index',array('child_school_id'=>$child_school_id)));
        }else{
            $db->rollback();
            $this->error('解绑失败');
        }
    }


}
